package com.room.search.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * By   : ghd.bright
 * Time : 2022/1/8
 * Description: 注解校验，校验对象
 */
public class BeanValidator {

    private static final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    private BeanValidator() {}

    public static String validate(Object object, Class<?>... groups) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<Object>> validate = validator.validate(object, groups);
        if (validate.isEmpty()) {
            return "";
        }

        StringBuilder errors = new StringBuilder();
        for (ConstraintViolation<Object> objectConstraintViolation : validate) {
            errors.append(objectConstraintViolation.getMessage()).append(",");
        }

        if (errors.length() > 0) {
            return errors.substring(0, errors.length() - 1);
        }
        return errors.toString();

    }
}
